package com.java.service.impl;

import com.java.dao.UserRoleMapper;
import com.java.dto.UserRoleDTO;
import com.java.model.Result;
import com.java.model.UserRole;
import com.java.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserRoleServiceImpl implements UserRoleService {

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public List<UserRole> list(int roleId) {
        return userRoleMapper.list(roleId);
    }

    @Transactional
    @Override
    public Result save(UserRoleDTO userRoleDTO) {
        // 1.删除管理员原有的角色
        userRoleMapper.removeByUserId(userRoleDTO.getUserId());
        // 2.如果有勾选角色，则为该管理员添加角色
        if (userRoleDTO.getRoleIds() != null && userRoleDTO.getRoleIds().length > 0) {
            for (int roleId : userRoleDTO.getRoleIds()) {
                UserRole userRole = new UserRole();
                userRole.setUserId(userRoleDTO.getUserId()); //设置新增管理员
                userRole.setRoleId(roleId); // 设置新增角色
                userRoleMapper.save(userRole);
            }
        }

        return Result.success();
    }
}
